package com.geline.easytrans.config;

import cn.hutool.core.util.ClassUtil;
import com.geline.easytrans.annotation.DictType;
import com.geline.easytrans.annotation.DictTypeScan;
import com.geline.easytrans.dict.IDict;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;
import java.util.Set;

/**
 * @DictType 注册器
 * 这个类会在一开始解析SpringSourceApplication启动类的时候
 * 通过解析@DictTypeScan注解中的@Import导入的，那么spring就会回调registerBeanDefinitions()方法
 *
 * @author: mengxin
 * @date: 2023/4/26 16:13
 */
@Slf4j
public class DictTypeScannerRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        Map<String, Object> objectMap = metadata.getAnnotationAttributes(DictTypeScan.class.getName());
        if(objectMap!=null){
            AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(objectMap);
            String[] basePackages = annoAttrs.getStringArray("value");
            initDictEnumRegistry(basePackages);
        }
    }

    public void initDictEnumRegistry(String[] scanBasePackages){
        for(String pck : scanBasePackages){
            Set<Class<?>> classes = ClassUtil.scanPackageByAnnotation(pck, DictType.class);
            if(classes!=null && !classes.isEmpty()){
                for(Class<?> clazz : classes){
                    DictType annotation = clazz.getAnnotation(DictType.class);
                    DictEnumRegistry.putEnumClass((Class<? extends IDict>) clazz, annotation.value(), annotation.label());
                }
            }
        }
        log.info(">>>> success to start @DictType = {}", DictEnumRegistry.getDictItems().size());
    }
}
